import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Button, Table, message, DatePicker, Input, Tooltip } from 'antd'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'

const { Item } = Form
// const { Option } = Select

const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '系列号',
      dataIndex: 'serieno',
      key: 'serieno',
      width: 150
    },
    {
      title: '案件数',
      dataIndex: 'case',
      key: 'case',
      width: 80,
      render: v => {
        return v.length || 0
      }
    },
    {
      title: '案号/收案号',
      dataIndex: 'caseno_info',
      key: 'caseno_info',
      ellipsis: {
        showTitle: false
      },
      render: s => (
        <Tooltip placement='topLeft' title={s}>
          {s}
        </Tooltip>
      )
    },
    {
      title: '标签',
      dataIndex: 'tag',
      key: 'tag',
      width: 150,
      ellipsis: {
        showTitle: false
      },
      render: s => (
        <Tooltip placement='topLeft' title={s}>
          {s}
        </Tooltip>
      )
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150,
      ellipsis: {
        showTitle: false
      },
      render: s => (
        <Tooltip placement='topLeft' title={s}>
          {s}
        </Tooltip>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      width: 150,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 180,
      render: (value, line) => {
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.openDetail(line)}>详情</span>
          </span>
        )
      }
    }
  ]
  return list
}

class SeriesCaseList extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '在办',
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  // 查看系列案详情
  openDetail (data) {
    this.props.addWindow({ id: `seriesCaseDetail-${data.id}`, title: `系列案-${data.serieno}`, componentName: 'SeriesCaseDetail', forceRefresh: false, meta: { id: data.id, editable: false } })
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, orderField, order } = this.state
    const { current, pageSize } = pagination
    const condition = []
    if (form.beginTime) {
      condition.push({ k: 'create_datetime', o: '>=', v: Math.floor(form.beginTime / 1000) })
    }
    if (form.endTime) {
      condition.push({ k: 'create_datetime', o: '<=', v: Math.floor(form.endTime / 1000) })
    }
    if (form.serieno) {
      condition.push({ k: 'serieno', o: 'like', v: `%${form.serieno}%` })
    }
    delete form.beginTime
    delete form.endTime
    const data = {
      current,
      page_size: pageSize,
      ...form,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    this.setState({ loading: true })
    this.$get('/api/xapc/caseserie', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取初始化数据
  getInitialValues () {
    const y = moment().year()
    const beginTime = moment(`${y}-01-01 00:00:00`)
    const endTime = moment()
    return {
      beginTime,
      endTime
    }
  }

  // 根据传参格式化搜索条件
  initByMate () {
    const c = this.formRef.current
    if (!c) {
      return setTimeout(() => {
        this.initByMate()
      }, 100)
    }
    const { serieno } = this.props.meta
    if (!serieno) {
      return this.getTableData()
    }
    c.resetFields()
    c.setFieldsValue({ serieno })
    c.submit()
  }

  componentDidUpdate (prev) {
    if (prev.serieno !== this.props.serieno) {
      this.initByMate()
    }
  }

  componentDidMount () {
    this.initByMate()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} initialValues={this.getInitialValues()} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item labelCol={{ flex: '80px' }} label='系列号' name='serieno'>
                    <Input placeholder='请输入系列号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='创建起始时间' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择起始时间' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束时间' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择结束时间' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                {/* <Col span={8}>
                  <Item label='立案员' name='accepter'>
                    <Select allowClear>
                      <Option key='张秘书'>张秘书</Option>
                      <Option key='黄秘书'>黄秘书</Option>
                    </Select>
                  </Item>
                </Col> */}
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SeriesCaseList)
